package com.nlx.notes.module.service.impl.loan;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.nlx.notes.module.bean.dto.loan.LoanBorrowerQueryDTO;
import com.nlx.notes.module.bean.dto.loan.LoanBorrowerSaveDTO;
import com.nlx.notes.module.bean.vo.loan.BorrowerInfoVO;
import com.nlx.notes.module.core.consts.GlobalConst;
import com.nlx.notes.module.core.enums.error.LoanCodeEnum;
import com.nlx.notes.module.core.util.DataConvertorUtils;
import com.nlx.notes.module.core.util.JSONUtils;
import com.nlx.notes.module.entity.BorrowerInfo;
import com.nlx.notes.module.mapper.loan.BorrowerInfoMapper;
import com.nlx.notes.module.service.loan.IBorrowerInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nlx.notes.support.handler.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 借款人信息 服务实现类
 * </p>
 *
 * @author nlx
 * @since 2025-10-25
 */
@Slf4j
@Service
public class BorrowerInfoServiceImpl extends ServiceImpl<BorrowerInfoMapper, BorrowerInfo> implements IBorrowerInfoService {


    @Override
    public List<BorrowerInfoVO> listByCondition(LoanBorrowerQueryDTO loanBorrowerQueryDTO) {
        List<BorrowerInfo> borrowerInfoList = this.getBaseMapper().selectList(Wrappers.lambdaQuery(BorrowerInfo.class)
                .eq(BorrowerInfo::getUserId, loanBorrowerQueryDTO.getUserId())
                .eq(BorrowerInfo::getDelFlag, GlobalConst.DEL_FLAG_NORMAL)
                .orderByDesc(BorrowerInfo::getId));
        if (borrowerInfoList != null && borrowerInfoList.size() > 0) {
            return DataConvertorUtils.copyListProperties(borrowerInfoList,BorrowerInfoVO::new);
        }
        return List.of();
    }

    @Override
    public BorrowerInfoVO saveBorrower(LoanBorrowerSaveDTO loanBorrowerSaveDTO) {
        //判断借款人是否已经存在
        BorrowerInfo borrowerInfo = findByBorrowerName(loanBorrowerSaveDTO.getName(),loanBorrowerSaveDTO.getUserId());
        if(borrowerInfo == null){
            borrowerInfo = new BorrowerInfo();
            borrowerInfo.setName(loanBorrowerSaveDTO.getName());
            borrowerInfo.setPhone(loanBorrowerSaveDTO.getPhone());
            borrowerInfo.setWechat(loanBorrowerSaveDTO.getWechat());
            borrowerInfo.setUserId(loanBorrowerSaveDTO.getUserId());
            borrowerInfo.setRemarks(loanBorrowerSaveDTO.getRemarks());
            borrowerInfo.setCreditScore(100);
            borrowerInfo.setCreatedTime(LocalDateTime.now());
            borrowerInfo.setDelFlag(GlobalConst.DEL_FLAG_NORMAL);
            boolean save = this.save(borrowerInfo);
            if(!save){
                log.error("保存用户的借款人信息失败，参数：{}",JSONUtils.toString(loanBorrowerSaveDTO));
            }
        }
        return DataConvertorUtils.copyProperties(borrowerInfo,BorrowerInfoVO::new);
    }

    @Override
    public BorrowerInfo findAndCheckById(Long borrowerId, Long userId) {
        if(null == borrowerId || null == userId){
            log.error("没有id或者用户id");
            throw new BusinessException(LoanCodeEnum.DATA_NOT_EXISTS_ERROR);
        }
        BorrowerInfo borrowerInfo = this.getBaseMapper().selectOne(Wrappers.lambdaQuery(BorrowerInfo.class)
                .eq(BorrowerInfo::getId, borrowerId).eq(BorrowerInfo::getUserId, userId)
                .eq(BorrowerInfo::getDelFlag, GlobalConst.DEL_FLAG_NORMAL), false);
        if(null == borrowerInfo){
            log.error("数据 {} 不存在或者不属于当前用户 {} ",borrowerId,userId);
            throw new BusinessException(LoanCodeEnum.DATA_NOT_EXISTS_ERROR);
        }
        return borrowerInfo;
    }


    @Override
    public BorrowerInfo findByBorrowerName(String name, Long userId) {
        if(StrUtil.isEmpty(name) || null == userId){
            return null;
        }
        return this.getBaseMapper().selectOne(Wrappers.lambdaQuery(BorrowerInfo.class).eq(BorrowerInfo::getName,name)
                .eq(BorrowerInfo::getUserId,userId)
                .eq(BorrowerInfo::getDelFlag,GlobalConst.DEL_FLAG_NORMAL),false);
    }
}
